package tech.util;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;

    //通过静态代码块来加载mybatis-config.xml文件
    static{
        try {
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession - 线程非安全的对象 - 负责进行CRUD操作
     * @return
     */

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    /**
     * 没必要写
     * @param sqlSession
     */
    public static void close(SqlSession sqlSession){
        if(null!=sqlSession){
            sqlSession.close();
        }
    }
}